<?php

namespace Frieza\Modules\Push\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\AdmPush\PushRule;
use Doraemon\model\AdmPush\PushType;
use hhz\constant\basic\pushChannel;

class PushRuleController extends Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 推送规则列表
     * @param Content $content
     * @return Content
     */
    public function list(Content $content, $channel='')
    {
        if(!$channel) {
            return redirect('/admin/push/pushRule/huawei');
        }
        $firstList = PushRule::selectByWhere([
            'channel' => $channel,
            'data_status' => PushRule::STATUS_NORMAL,
            'ORDER' => ['sort' => 'ASC']
        ]);
        $typeTimes = $typeNames = [];
        $pushTypes = PushType::selectByWhere([
            'pid' => PushType::DEFAULT_PID,
            'type_time[!]' => '[]',
            'data_status' => PushType::STATUS_NORMAL,
            'ORDER' => ['sort' => 'ASC']
        ]);
        foreach($pushTypes as $item) {
            $times = json_decode($item['type_time'], true);
            $typeTimes[$item['type_name']] = $times;
            $typeNames[$item['type_name']] = $item['type_desc'];
        }
        $showTypes = array_keys($typeTimes);
        foreach($firstList as $key => $row) {
            if(!in_array($row['push_type'], $showTypes)) {
                unset($firstList[$key]);
            }
        }
        $gridModel = new pGridDataModel($firstList);
        $categoryGird = Admin::grid($gridModel, function (Grid $grid) use ($typeTimes, $typeNames) {
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disablePagination();
            $grid->disableCreateButton();
            $grid->column('id');
            $grid->column('channel', '通道')->display(function () {
                return pushChannel::GROUP_ALL[$this->channel];
            });
            $grid->column('push_type', '推送类型')->display(function () use ($typeNames) {
                return "{$typeNames[$this->push_type]}({$this->push_type})";
            });
            $grid->column('rule', '推送规则')->display(function () use ($typeTimes) {
                $rules = json_decode($this->rule, true);
                $infoRules = array_column($rules, null, 'type_time');
                $format = [];
                foreach($typeTimes[$this->push_type] as $typeTime) {
                    if($infoRules[$typeTime]) {
                        $format[] = $infoRules[$typeTime];
                    } else {
                        $format[] = ['type_time'=>$typeTime, 'start_date'=>'', 'end_date'=>'', 'switch'=>"1"];
                    }
                }
                foreach($format as $key => $item) {
                    if($item['switch'] == "1") {
                        $format[$key]['switch'] = " ✅开启";
                    } else {
                        $format[$key]['switch'] = "🚫关闭";
                    }
                    if(!$item['start_date']) {
                        $format[$key]['start_date'] = "-";
                    }
                    if(!$item['end_date']) {
                        $format[$key]['end_date'] = "-";
                    }
                }
                return $format;
            })->table([
                'type_time' => '推送时间',
                'start_date' => '开始日期',
                'end_date' => '结束日期',
                'switch' => '开关',
            ]);
            /*
            $grid->column('data_status', '数据状态')->display(function () {
                $status = PushRule::STATUS_ARR[$this->data_status];
                return $status;
            })->label([
                1 => 'info',
                9 => 'default',
            ]);
             */
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableView();
                //获取推送规则的状态,隐藏状态的不显示操作
                $id = $actions->row->id;
                $rank_info = PushRule::getByWhere(['id' => $id]);
                if ($rank_info['data_status'] == PushRule::STATUS_DELETED){
                    $actions->disableEdit();
                }
            });
        });
        $tab = new Tab();
        foreach(PushRule::CHANNEL as $item) {
            $name = pushChannel::GROUP_ALL[$item];
            if($item == $channel) {
                $tab->add("{$name}通道推送规则", $categoryGird->render(), true);
            } else {
                $tab->addLink("{$name}通道推送规则", url("admin/push/pushRule/{$item}"));
            }
        }
        $content->row($tab);
        return $content
            ->header('通道推送规则管理')
            ->description(' ')
            ->breadcrumb(['text' => '通道推送规则管理']);
    }

    /**
     * 推送规则编辑页
     * @param Content $content
     * @param int $id
     * @return Content
     */
    public function edit(Content $content, $channel, $id)
    {
        $tab = new Tab();
        //基础信息
        $info = [];
        $header = "编辑规则";
        $info = PushRule::getByWhere(['id' => $id]);

        $rule = json_decode($info['rule'], true);
        $pushType = PushType::getByWhere([
            'pid' => PushType::DEFAULT_PID,
            'type_name' => $info['push_type'],
            'data_status' => PushType::STATUS_NORMAL,
            'ORDER' => ['sort' => 'ASC']
        ]);
        $times = json_decode($pushType['type_time'], true);
        $rules = [];
        $infoRule = array_column($rule, null, 'type_time');
        foreach($times as $item) {
            if($infoRule[$item]) {
                $rules[] = $infoRule[$item];
            } else {
                $rules[] = [ 'type_time' => $item ];
            }
        }
        $info['rule'] = $rules;

        $basicForm = new Form($info);
        $basicForm->text('channel', '推送通道')->readOnly();
        $basicForm->text('push_type', '推送类型')->readOnly();
        $basicForm->table('rule', '规则', function ($table) {
            $table->text('type_time', '触发时间')->readOnly();
            $table->date('start_date', '开始日期')->format('YYYY-MM-DD')->width(300);
            $table->date('end_date', '结束日期')->format('YYYY-MM-DD')->width(300);
            $table->radio('switch', '开关')->options(["1"=>'开启', "0"=>'关闭'])->default("1");
        })->disableCreate();

        $basicForm->action('/admin/push/pushRule/' . $id . '/save');
        $tab->add('推送规则', $basicForm);
        $content->header($header . "-" . $info['channel'] . '-' . $info['push_type'])
            ->breadcrumb([
                'text' => '推送规则管理',
                'url' => '/push/pushRule'
            ], ['text' => '规则编辑'])
            ->row($tab);
        return $content;
    }

    /**
     * 保存推送规则
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function save(Request $request, $id)
    {
        $data = [];
        $data['channel'] = $request->input('channel');
        $data['rule'] = array_filter($request->input('rule'), function($rule) {
            return $rule['_remove_'] == "0";
        });
        $data['rule'] = array_values($data['rule']);
        try {
            $ret = PushRule::updateData($data, ['id' => $id]);
            if($ret == false) {
                throw new \Exception('保存数据异常');
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect("/admin/push/pushRule/{$data['channel']}")->with(compact('success'));
    }
}
